<template>
  <view class="container">
    <!-- 空白页 -->
    <view v-if="!hasLogin || empty" class="empty">
      <image src="/static/emptyCart.jpg" mode="aspectFit"></image>
      <view v-if="hasLogin" class="empty-tips">
        空空如也
        <navigator class="navigator" url="../index/index" open-type="switchTab">随便逛逛></navigator>
      </view>
      <view v-else class="empty-tips">
        空空如也
        <view class="navigator" @click="navToLogin">去登录></view>
      </view>
    </view>

    <!-- 购物车列表 -->
    <view v-else class="cart-list">
      <block v-for="(item, index) in cartList" :key="item.id">
        <view class="cart-item" :class="{'b-b': index !== cartList.length - 1}">
          <view class="image-wrapper">
            <image :src="item.image" mode="aspectFill"></image>
            <view class="yticon icon-xuanzhong2 checkbox" :class="{checked: item.checked}" @click="check('item', index)"></view>
          </view>
          <view class="item-right">
            <text class="clamp title">{{ item.name }}</text>
            <text class="price">¥{{ item.price }}</text>
            <uni-number-box
                class="step"
                :min="1"
                :max="item.stock"
                :value="item.quantity"
                :index="index"
                @eventChange="numberChange"
            ></uni-number-box>
          </view>
          <text class="del-btn yticon icon-fork" @click="deleteCartItem(index)"></text>
        </view>
      </block>
    </view>

    <!-- 底部菜单栏 -->
    <view class="action-section">
      <view class="checkbox">
        <image :src="allChecked ? '/static/selected.png' : '/static/select.png'" mode="aspectFit" @click="check('all')"></image>
        <view class="clear-btn" :class="{show: allChecked}" @click="clearCart">清空</view>
      </view>
      <view class="total-box">
        <text class="price">¥{{ total }}</text>
      </view>
      <button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
    </view>
  </view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
			};
		},
    onShow() {
      this.getCart(); // 每次页面显示时刷新数据
      this.total = 0; //总价格
      this.allChecked = false;
    },
		onLoad(){
			this.getCart();
		},
		watch:{
			//显示空白页
			cartList(e){
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		computed:{
			...mapState(['hasLogin'])
		},
		methods: {
			//请求数据
      async getCart() {
        const userId = uni.getStorageSync('token'); // 获取当前用户的 ID
        const result = await uni.request({
          url: 'http://localhost:8080/app/api/cart/get',
          method: 'GET',
          data: {
            userId: userId
          }
        });
        console.log("购物车数据：",result[1].data.data)
        if (result[1].statusCode === 200) {
          this.cartList = Object.values(result[1].data.data); // 将购物车数据转换为数组
        } else {
          uni.showToast({
            title: '获取购物车失败',
            icon: 'none'
          });
        }
      },

			navToLogin(){
				uni.navigateTo({
					url: '/pages/public/login'
				})
			},
      // 更新总价
      updateTotal() {
        this.total = this.cartList.reduce((sum, item) => {
          return item.checked ? sum + item.price * item.quantity : sum;
        }, 0);
      },
      //商品选中变化
      check(type, index) {
        if (type === 'item') {
          this.cartList[index].checked = !this.cartList[index].checked;
        } else {
          const checked = !this.allChecked;
          this.cartList.forEach(item => item.checked = checked);
          this.allChecked = checked;
        }
        this.updateTotal();
      },
      // 删除商品
      async deleteCartItem(index) {
        const item = this.cartList[index];
        const userId = uni.getStorageSync('token'); // 获取用户ID
        try {
          const result = await uni.request({
            url: `http://localhost:8080/app/api/cart/delete?userId=${userId}`,
            method: 'POST',
            data: {
              id: item.id, // cartItem 的属性
              name: item.name,
              price: item.price,
              quantity: item.quantity,
              image: item.image,
            },
          });
          console.log("删除返回结果：",result[1])
          if (result[1].statusCode === 200) {
            this.cartList.splice(index, 1); // 从购物车列表中移除商品
            this.updateTotal(); // 更新总价
            uni.showToast({ title: '删除成功', icon: 'success' });
          } else {
            uni.showToast({ title: '删除失败', icon: 'none' });
          }
        } catch (error) {
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      },
      // 清空购物车
      async clearCart() {
        const userId = uni.getStorageSync('token'); // 获取用户ID
        try {
          const result = await uni.request({
            url: `http://localhost:8080/app/api/cart/clear?userId=${userId}`,
            method: 'POST',
          });

          if (result[1].statusCode === 200) {
            this.cartList = []; // 清空购物车列表
            this.updateTotal(); // 更新总价
            uni.showToast({ title: '清空成功', icon: 'success' });
          } else {
            uni.showToast({ title: '清空失败', icon: 'none' });
          }
        } catch (error) {
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
        this.allChecked = false //全选状态  true|false
      },
      // 数量变化事件
      numberChange(data) {
        const index = data.index;
        const newQuantity = data.number;

        // 更新数量
        this.$set(this.cartList[index], 'quantity', newQuantity);

        // 更新总价
        this.updateTotal();
      },
      //创建订单，校验库存
      async createOrder() {
        // 获取选中的商品
        let list = this.cartList;
        let goodsData = [];
        let goodsStock = [];
        list.forEach(item => {
          if (item.checked) {
            goodsStock.push({
              id: item.id, // 商品 ID
              quantity: item.quantity // 商品数量
            });
            goodsData.push(item); // 选中的商品数据
          }
        });

        // 如果没有选中商品，提示用户
        if (goodsData.length === 0) {
          uni.showToast({
            title: '请选择商品',
            icon: 'none'
          });
          return;
        }

        // 向后端发送请求，检查库存
        try {
          const result = await uni.request({
            url: 'http://localhost:8080/app/api/cart/checkStock', // 后端库存检查接口
            method: 'POST',
            data: goodsStock,
          });

          console.log("库存检查结果：", result[1]);

          if (result[1].statusCode === 200) {
            const response = result[1].data;
            if (response.success) {  //库存充足
              // 跳转到订单创建页面
              const goodsDataString = JSON.stringify(goodsData);
              uni.navigateTo({
                url: `/pages/order/createProductOrder?data=${encodeURIComponent(goodsDataString)}`,
              });

            } else {  // 库存不足，提示用户
              let message = response.message || '库存不足';
              if (response.data) {
                response.data.forEach(item => {
                  if (!item.isEnough) {
                    message += `\n商品 ${item.id} 库存不足，当前库存：${item.stock}`;
                  }
                });
              }
              uni.showToast({
                title: message,
                icon: 'none',
                duration: 3000 // 提示时间稍长
              });
            }
          } else {
            uni.showToast({
              title: '库存检查失败',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
          console.error("库存检查请求失败：", error);
        }
      },
		}
	}
</script>

<style lang='scss'>
	.container{
		padding-bottom: 134upx;
		/* 空白页 */
		.empty{
			position:fixed;
			left: 0;
			top:0;
			width: 100%;
			height: 100vh;
			padding-bottom:100upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #fff;
			image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			}
			.empty-tips{
				display:flex;
				font-size: $font-sm+2upx;
				color: $font-color-disabled;
				.navigator{
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}
	/* 购物车列表项 */
	.cart-item{
		display:flex;
		position:relative;
		padding:30upx 40upx;
		.image-wrapper{
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position:relative;
			image{
				border-radius:8upx;
			}
		}
		.checkbox{
			position:absolute;
			left:-16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 4upx;
			color: $font-color-disabled;
			background:#fff;
			border-radius: 50px;
		}
		.item-right{
			display:flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position:relative;
			padding-left: 30upx;
			.title,.price{
				font-size:$font-base + 2upx;
				color: $font-color-dark;
				height: 40upx;
				line-height: 40upx;
			}
			.attr{
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				height: 50upx;
				line-height: 50upx;
			}
			.price{
				height: 50upx;
				line-height:50upx;
			}
		}
		.del-btn{
			padding:4upx 10upx;
			font-size:34upx;
			height: 50upx;
			color: $font-color-light;
		}
	}
	/* 底部栏 */
	.action-section{
		/* #ifdef H5 */
		margin-bottom:100upx;
		/* #endif */
		position:fixed;
		left: 30upx;
		bottom:30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 690upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255,255,255,.9);
		box-shadow: 0 0 20upx 0 rgba(0,0,0,.5);
		border-radius: 16upx;
		.checkbox{
			height:52upx;
			position:relative;
			image{
				width: 52upx;
				height: 100%;
				position:relative;
				z-index: 5;
			}
		}
		.clear-btn{
			position:absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius:0 50px 50px 0;
			opacity: 0;
			transition: .2s;
			&.show{
				opacity: 1;
				width: 120upx;
			}
		}
		.total-box{
			flex: 1;
			display:flex;
			flex-direction: column;
			text-align:right;
			padding-right: 40upx;
			.price{
				font-size: $font-lg;
				color: $font-color-dark;
			}
			.coupon{
				font-size: $font-sm;
				color: $font-color-light;
				text{
					color: $font-color-dark;
				}
			}
		}
		.confirm-btn{
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}
	}
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked{
		color: $uni-color-primary;
	}
</style>
